# -*- coding: utf-8 -*-

# graphic-pppoe-client - Easy graphic networking manager
#
# Author: GoTLiuM InSPiRiT <gotlium@gmail.com>
#
# Copyright 2010, GoTLiuM InSPiRiT <gotlium@gmail.com>.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.


import os, sys
from fs import *
from los import isRunned

class NullDevice(object):
	def write(self, s):
		pass


class Daemon(object):
	pid_file = None

	def _onExit(self):
		if delFile(self.pid_file):
			print "> Old pid file removed"

	def init(self, pid_file = '/tmp/daemon.pid', dir = '/', umask = 0, term = 0):
		self.pid_file = pid_file
		if isRunned(pid_file):
			print "Already runned."
			sys.exit(1)

		try:
			pid = os.fork()
		except OSError, e:
			raise Exception, "%s [%d]" % (e.strerror, e.errno)

		if pid == 0:
			os.chdir(dir)
			os.setsid()
			os.umask(umask)
			putFile(pid_file, "%d" % os.getpid())
			if not term:
				sys.stdin.close()
				sys.stdout = NullDevice()
				sys.stderr = NullDevice()
		elif pid == -1:
			print "Status: failed ..."
			print "error to fork!"
			sys.exit(0)
		else:
			print "Status: success."
			print "daemon pid: %d" % pid
			sys.exit(0)
